import {useState, useEffect} from 'react';
import {Box, CircularProgress} from '@mui/material';
import ArticleCard from '@components/front/articleCard';
import {queryArticleList} from '@services/front/article';

export default function ArticleList() {
    const [articles, setArticles] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const articlesData = await queryArticleList({});
                setArticles(articlesData);
            } catch (error) {
                console.error('Error fetching articles:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, []);

    return (
        <Box sx={{
            flex: 3.5,
            minWidth: 0,
            display: 'grid',
            gridTemplateColumns: {
                xs: '1fr',
                md: 'repeat(2, 1fr)'
            },
            gap: 2,
        }}>
            {loading ? (
                <Box
                    sx={{
                        cursor: 'pointer',
                        transition: 'transform 0.3s',
                        '&:hover': {
                            zIndex: 2,
                            transform: 'scale(1.02)',
                            boxShadow: '0 0 10px rgba(0, 0, 0, 0.2)'
                        }
                    }}
                >
                    <CircularProgress/>
                </Box>
            ) : (
                articles.map(article => (
                    <Box
                        key={article.id}
                        sx={{
                            cursor: 'pointer',
                            transition: 'transform 0.3s',
                            '&:hover': {
                                zIndex: 2,
                                transform: 'scale(1.02)',
                                boxShadow: '0 0 10px rgba(0, 0, 0, 0.2)'
                            }
                        }}
                    >
                        <ArticleCard {...article}/>
                    </Box>
                ))
            )}
        </Box>
    );
}
